package ru.dartit.android.apps.ucabinet.io;

import android.util.Log;
import ru.dartit.android.apps.ucabinet.Constants;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * @author gradusnik
 */

public class HttpsConnector {

  public static final String TAG = HttpsConnector.class.getSimpleName();

  public static String readUrl(Map<String,String> params) throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append(Constants.UCABINET_API_URL).append('?');
    for (String key : params.keySet()) {
      sb.append(key).append('=').append(params.get(key)).append('&');
    }
    Log.i(TAG, "Connect to url: " + sb.toString());

    URL url = new URL(sb.toString());
    HttpURLConnection http;
    if (url.getProtocol().toLowerCase().equals("https")) {
      trustAllHosts();
      HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
      https.setHostnameVerifier(DO_NOT_VERIFY);
      http = https;
    } else {
      http = (HttpURLConnection) url.openConnection();
    }

    return convertStreamToString(http.getInputStream());
  }

  /**
   * Trust every server - dont check for any certificate
   */
  private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
      new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
          return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
      }
    };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
      Writer writer = new StringWriter();
      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
      } finally {
        is.close();
      }
      return writer.toString();
    } else {
      return "";
    }
  }

  // always verify the host - dont check for certificate
  final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  };
}
